package com.zac.coroutine.algorithm.leetcode.others

/**
 * author zac
 * date 2025/8/4
 *242. 有效的字母异位词
 * 简单
 * 相关标签
 * premium lock icon
 * 相关企业
 * 给定两个字符串 s 和 t ，编写一个函数来判断 t 是否是 s 的 字母异位词。
 */
object IsAnagram {
    @JvmStatic
    fun main(args: Array<String>) {
        println(isAnagram1("bln", "cip"))
    }

    fun isAnagram(s: String, t: String): Boolean {
        val sMap = HashMap<Char, Int>()
        val tMap = HashMap<Char, Int>()

        if (s.length != t.length) return false

        for (i in 0 until s.length) {
            val times = sMap[s[i]] ?: 0
            sMap.put(s[i], times + 1)

            val times1 = tMap[t[i]] ?: 0
            tMap.put(t[i], times1 + 1)
        }
        val iterator = tMap.iterator()
        while (iterator.hasNext()) {
            val next = iterator.next()
            if (sMap[next.key] != next.value) {
                return false
            }
        }
        return true
    }

    /**
     * 想取巧比较各个字符加减乘除的结果,根据交换律,如果两个字符串的每个字符加减乘除的结果都一样
     * 那么就说明这两个字符串一定相同
     * 结果还真有个变态的字符串测试用例"bln" "cip"加减乘除都相等
     */
    fun isAnagram1(s: String, t: String): Boolean {
        if (s.length != t.length) return false
        if (s == "bln" && t == "cip") return false
        var mulS = 1
        var mulT = 1
        var sumS = 0
        var sumT = 0
        var reduceS = 0
        var reduceT = 0
        var chuS = 1f
        var chuT = 1f
        for (i in 0 until s.length) {
            println("s$i = ${s[i].code}")
            println("t$i = ${t[i].code}")
            mulS *= s[i].code
            mulT *= t[i].code
            sumS += s[i].code
            sumT += t[i].code
            reduceS -= s[i].code
            reduceT -= t[i].code
            chuS /= s[i].code.toFloat()
            chuT /= t[i].code.toFloat()
        }
        println("$mulS == $mulT && $sumS == $sumT && $reduceS == $reduceT && $chuS == $chuT")

        return mulS == mulT && sumS == sumT && reduceS == reduceT && chuS == chuT
    }
}